'''
Created on Jun 27, 2012

@author: cgiacofe
'''

import urllib2
import re
import os

file_list = ['hma_start.py',
             'logging.py',
             'serverstats.py',
             'updater.py']

trunk = 'http://hma-manager.googlecode.com/svn/trunk/scripts'

def get_svn_version():
    data = urllib2.urlopen('http://hma-manager.googlecode.com/svn/trunk/scripts/').read()
    revision = re.search(r'[a-zA-Z]+ [0-9]+', data)
    
    return revision.group()

def new_version(old_version):
    '''Checks whether the current script in main directory is a newer version
    than when the script was first started.
    
    @param old_ver: Currently running version of the script
    @type old_ver: string
    
    @return: Revision number if a new version is available to run, otherwise returns 0.
    '''
    try:
        new_ver = float(get_svn_version().split()[1])
        old_ver = float(old_version)
    except:
        new_ver = 0
        
    if new_ver > old_ver:
        return new_ver
    else:
        return 0

def download_new_version(config_file):
    try:
        for source_file in file_list:
            url = os.path.join(trunk,source_file)
            _download_file(url)
            
    except:
        return False
    
    config = open(config_file,'w')
    config.write(get_svn_version())
    return True

def _download_file(url):
    # Open the url

    f = urllib2.urlopen(url)
    print "downloading " + url

    # Open our local file for writing
    with open(os.path.basename(url), "wb") as local_file:
        local_file.write(f.read())
 
    
if __name__ == '__main__':
    pass